package com.platform.common.interceptor;

import com.platform.common.annotations.ResponseResult;
import com.platform.common.util.CommonConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * describe:API统一返回样式的拦截器
 *
 * @author rainly
 * @date 2019/11/29
 * @time 9:47 上午
 */
@Slf4j
public class ResponseResultInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            /*
              判断是否在类或方法上使用了ResponseResult注解
             */
            if (clazz.isAnnotationPresent(ResponseResult.class)) {
                request.setAttribute(CommonConst.RESPONSE_RESULT_ANN, clazz.getAnnotation(ResponseResult.class));
            }
            if (method.isAnnotationPresent(ResponseResult.class)) {
                request.setAttribute(CommonConst.RESPONSE_RESULT_ANN, method.getAnnotation(ResponseResult.class));
            }
        }
        return true;
    }
}